<?php
// +----------------------------------------------------------------------
// | 中间件 - 路由日志记录
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\middleware;

use app\Request;
use app\model\SystemUsersLogsModel;

class RouteLogRecord
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        if ($request->route('type') === 'admin') {
            // 记录admin操作日志
            if ($record = $request->route('record')) {
                // 不记录密码
                $body = $request->param();
                if (isset($body['password'])) {
                    $body['password'] = '************';
                }
                (new SystemUsersLogsModel())->save([
                    'type' => $record['type'],
                    'user_id' => $request->getUserId(),
                    'summary' => $record['summary'],
                    'url' => $request->url(),
                    'method' => $request->method(),
                    'body' => $body,
                    'user_agent' => $request->header('user-agent'),
                    'user_info' => $request->getUserInfo(),
                    'ip_address' => $request->ip(),
                    // todo: 这里需要获取用户IP归属地
                    'ip_location' => '中国口口省口口市'
                ]);
            }
        }
        return $response;
    }
}
